<script setup lang="ts">
import DirectItem from './components/direct-item.vue';
import AccItem from './components/acc-item.vue';
import AccFilterPop from './components/acc-filter-pop.vue';
import { useAccCommon } from './composables/use-acc-common';
import type { CustomerObj, ContactDtl } from './types';

const appStore = useAppStore();
const directStore = useDirectStore();

const customerObj = ref<CustomerObj>({} as CustomerObj);
const contactObj = ref<ContactDtl>({} as ContactDtl);
const statusList = ref([{ name: '未提交' }, { name: '已提交' }]);
const currentStatus = ref(0);
const filterShow = ref(false);
const deleteShow = ref(false);
const deleteItem = ref({});

const options = ref([
  {
    text: '作废',
    style: {
      backgroundColor: '#EE0A24',
    },
  },
]);

const filterVal = ref<any>({
  orderId: '',
  start: '',
  end: '',
  tranposId: '',
  tranposName: '',
  logistCenterId: '',
  logistCenterName: '',
  reasonId: '',
  reasonName: '',
  directrgMan: '',
});

const {
  tranposList,
  logistList,
  userList,
  reasonList,
  loading,
  fetchTranposList,
  fetchLogistList,
  fetchUserList,
} = useAccCommon();

const { list, totalNum, paginationLoading, resetAndFetchData, loadMore } = useSimplePagination(10);

/**
 * 获取订单列表数据
 */
const fetchData = async ({ pageNum, pageSize }: { pageNum: number; pageSize: number }) => {
  const { orderId, tranposId, logistCenterId, reasonId, directrgMan, start, end } = filterVal.value;
  const params = {
    customId: customerObj.value.customId,
    contactId: contactObj.value.contactId || '',
    entryId: customerObj.value.entryId,
    type: +currentStatus.value + 1,
    orderId,
    start,
    end,
    address: tranposId,
    logistCenter: logistCenterId,
    reason: reasonId,
    person: directrgMan,
    pageNum,
    pageSize,
  };

  const response = await DirectService.queryOrderList(params);

  return {
    list: response.list || [],
    total: response.total || 0,
  };
};

/**
 * 切换状态标签
 */
const handleChange = ({ index }: { index: number }) => {
  currentStatus.value = index;
  resetAndFetchData(fetchData);
};

/**
 * 新增订单
 */
const handleAdd = () => {
  // 清空 store 中的详情数据，确保是新增模式
  directStore.setDirectDetailObj({});
  router.push(RouteMap.directAdd);
};

/**
 * 删除订单
 */
const handleDelete = async (item: any) => {
  uni.showModal({
    content: '是否确认作废该条总单',
    success: async (res: any) => {
      if (res.confirm) {
        await DirectService.deleteOrder({ orderId: item.orderId });
        showSuccess('删除成功');
        resetAndFetchData(fetchData);
      }
    },
  });
};

/**
 * 查看订单详情
 */
const toDetail = (item: any) => {
  directStore.setDirectDetailObj(item);
  router.push(RouteMap.directDetail);
};

/**
 * 筛选条件确认
 */
const handleFilterConfirm = (filterData: any) => {
  filterShow.value = false;
  filterVal.value = filterData;
  resetAndFetchData(fetchData);
};

onMounted(() => {
  customerObj.value = directStore.customerObj;
  contactObj.value = directStore.contactObj;

  // 初始化数据
  fetchTranposList();

  // 加载列表数据
  resetAndFetchData(fetchData);
});

onShow(() => {
  if (appStore.hadDoneOnDetail) {
    // 刷新列表数据
    resetAndFetchData(fetchData);
    // 重置标志，避免下次重复刷新
    appStore.setHadDoneOnDetail(false);
    // 重置detail页面的刷新标记
    directStore.setOrderDetailRefreshed(false);
  }
});

onReachBottom(() => {
  loadMore(fetchData);
});
</script>

<template>
  <view class="px-4 pt-10 pb-100">
    <view class="text-17 flex font-bold">
      <view class="color-main-3">直调</view>
      <view>验收</view>
    </view>
    <view class="view-shadow mt-2 p-4">
      <direct-item title="客户" :content="`${customerObj.customId}/${customerObj.customName}`" />
      <direct-item
        v-if="contactObj.contactId"
        title="分支机构"
        :content="`${contactObj.contactId}/${contactObj.contactName}`"
        class="mt-1"
      />
    </view>
    <view class="view-shadow mt-2">
      <up-tabs
        :current="currentStatus"
        :list="statusList"
        :scrollable="false"
        :lineWidth="40"
        @change="handleChange"
      />
    </view>
    <up-swipe-action>
      <up-swipe-action-item
        v-for="item in list"
        :key="item.id"
        class="block rounded-20rpx overflow-hidden mt-2"
        :options="options"
        :disabled="currentStatus === 1"
        @click="handleDelete(item)"
      >
        <acc-item :data="item" @click="toDetail(item)" />
      </up-swipe-action-item>
    </up-swipe-action>
    <up-loadmore
      v-if="paginationLoading || list.length < totalNum"
      :status="paginationLoading ? 'loading' : 'loadmore'"
    />
    <view class="view-shadow mt-2">
      <app-empty
        v-show="!paginationLoading && !list.length"
        class="block py-3"
        description="暂无总单"
      />
    </view>
    <app-bottom-actions :count="currentStatus === 0 ? 2 : 1">
      <app-action-btn class="flex-1" text="条件筛选" @click="filterShow = true" />
      <app-action-btn
        v-if="currentStatus === 0"
        class="flex-1"
        text="新增"
        type="primary"
        @click="handleAdd"
      />
    </app-bottom-actions>
    <acc-filter-pop
      v-model:filterShow="filterShow"
      :filterVal="filterVal"
      :tranposList="tranposList"
      :logistList="logistList"
      :userList="userList"
      :reasonList="reasonList"
      :fetchLogistList="fetchLogistList"
      :fetchUserList="fetchUserList"
      @confirm="handleFilterConfirm"
    />
  </view>
</template>
